package os.t2;

public class Reader implements Runnable{
    Resources resources;
    public Reader(Resources resources){
        this.resources=resources;
    }
    @Override
    public void run() {
        try{
            while (true) {
                resources.rMutex.acquire();//获取读者资源
                if (resources.readCount == 0) {//如果是第一个读者来了
                    resources.wMutex.acquire();//获取写着资源，防止在读的时候有写着写
                }
                resources.readCount++;//读者数量加1
                resources.rMutex.release();//释放读者资源

                System.out.println(resources.readCount + "号读者在读..." + Thread.currentThread().getName());

                resources.rMutex.acquire();
                resources.readCount--;
                if (resources.readCount == 0) {//最后一个读者
                    resources.wMutex.release();//释放写者资源
                }
                resources.rMutex.release();
                Thread.sleep(300);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
